/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import ascii2mathmlconverter.ASCII2MathML;
import com.oreilly.servlet.MultipartRequest;
import formulagraph.Canvas;
import formulagraph.Colores;
import formulagraph.Dominio;
import formulagraph.Ejes;
import formulagraph.Formula;
import formulagraph.lineas.Cadena;
import formulagraph.lineas.Continua;
import formulagraph.lineas.ExtremosLinea;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author soler4888
 */
public class DibujarSVG extends HttpServlet {

    private static final int MAX_NUM_ASCII = 3;
    private static final int MAX_NUM_FILE = 3;
    private String filePath;

    @Override
    public void init(ServletConfig config) throws ServletException {
        // Obtener un contexto para ubicar los archivos 
        // en la ruta del servidor especificada (FormulaGraph/build/web/upload-files)
        filePath = config.getServletContext().getRealPath("/") + "upload-files";
    }

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        // Limite de tamaño de fichero 5 MB
        MultipartRequest mpr = new MultipartRequest(request, filePath, 5 * 1024 * 1024);

        try {
            // Canvas para pintar las funciones
            Integer xini = Integer.parseInt(mpr.getParameter("xini"));
            Integer xfin = Integer.parseInt(mpr.getParameter("xfin"));
            Integer yini = Integer.parseInt(mpr.getParameter("yini"));
            Integer yfin = Integer.parseInt(mpr.getParameter("yfin"));
            
            double anchuraX = (xfin - xini) / 500D;
            double anchuraY = (yfin - yini) / 500D;

            // width 400
            // height 400
            Ejes ejes = new Ejes(xini,
                    yini,
                    xfin,
                    yfin,
                    new Cadena((int) (20 * anchuraX), Colores.black, anchuraX, ExtremosLinea.round),
                    new Cadena((int) (20 * anchuraY), Colores.black, anchuraY, ExtremosLinea.round));
            Canvas canvas = new Canvas(xini, yfin, xfin - xini, yfin - yini);
            canvas.setEjes(ejes);


            // Lista de funciones ASCII para recolocar en los input
            List<String> funcionesascii = new ArrayList<String>(MAX_NUM_ASCII);
            // Lista de colores para las funciones ASCII
            List<String> colores = new ArrayList<String>(MAX_NUM_ASCII);
            // Conversor de ASCII a MathML
            ASCII2MathML converter = new ASCII2MathML();
            // Obtenemos todas las entradas ASCII que se hayan rellenado
            for (int i = 1; i <= MAX_NUM_ASCII; i++) {
                String temp = mpr.getParameter("ascii" + i);
                if (temp != null && !temp.equals("")) {
                    funcionesascii.add(temp);
                    String color = mpr.getParameter("color" + i);
                    colores.add(color);
                    FileOutputStream fos = new FileOutputStream(new File(filePath, "ascii" + i));
                    fos.write(converter.parse(temp).getBytes());
                    fos.close();
                    Formula f = new Formula(filePath,
                            "ascii" + i,
                            new Dominio(xini, xfin),
                            new Continua(Colores.valueOf(color), anchuraX, ExtremosLinea.butt),
                            canvas.getWidth() / 1000);
                    canvas.addFormula(f);
                }
            }
            // Obtenemos todas las entradas File que se hayan rellenado
            for (int i = 1; i <= MAX_NUM_ASCII; i++) {
                File temp = mpr.getFile("file" + i);
                if (temp != null) {
                    Formula f = new Formula(filePath,
                            "file" + i,
                            new Dominio(xini, xfin),
                            new Continua(Colores.black, anchuraX, ExtremosLinea.butt),
                            canvas.getWidth() / 1000);
                    canvas.addFormula(f);
                }
            }
            request.setAttribute("funcionesascii", funcionesascii);
            request.setAttribute("colores", colores);
            request.setAttribute("xini", xini);
            request.setAttribute("xfin", xfin);
            request.setAttribute("yini", yini);
            request.setAttribute("yfin", yfin);

            request.setAttribute("canvas", canvas);
            RequestDispatcher rd = request.getRequestDispatcher("/mathml.jsp");
            rd.forward(request, response);
        } catch (Exception ex) {
            request.getSession().setAttribute("error", "No se puede crear el MathML");
            RequestDispatcher rd = request.getRequestDispatcher("/mathml.jsp");
            rd.forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
